// 全局变量
let ratingChart = null;
let currentRating = 0;
let isAdmin = false;

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    loadComments();
    loadStats();
    setupEventListeners();
});

// 事件监听器
function setupEventListeners() {
    // 评分星星点击
    document.querySelectorAll('.rating-input i').forEach(star => {
        star.addEventListener('click', function() {
            const rating = parseInt(this.dataset.rating);
            setRating(rating);
        });
    });

    // 分类筛选
    document.getElementById('categoryFilter').addEventListener('change', function() {
        loadComments(this.value);
    });

    // 表单提交
    document.getElementById('commentForm').addEventListener('submit', function(e) {
        e.preventDefault();
        submitComment();
    });
}

// 设置评分
function setRating(rating) {
    currentRating = rating;
    const stars = document.querySelectorAll('.rating-input i');
    stars.forEach((star, index) => {
        if (index < rating) {
            star.className = 'fas fa-star';
        } else {
            star.className = 'far fa-star';
        }
    });
    document.getElementById('ratingInput').value = rating;
}

// 加载评论
async function loadComments(category = 'all') {
    try {
        const response = await fetch('/api/comments');
        const comments = await response.json();
        
        let filteredComments = comments;
        if (category !== 'all') {
            filteredComments = comments.filter(c => c.category === category);
        }
        
        displayComments(filteredComments);
    } catch (error) {
        console.error('加载评论失败:', error);
    }
}

// 显示评论
function displayComments(comments) {
    const container = document.getElementById('commentsList');
    container.innerHTML = '';
    
    if (comments.length === 0) {
        container.innerHTML = '<p class="text-center text-muted">暂无评论</p>';
        return;
    }
    
    comments.forEach(comment => {
        const commentDiv = document.createElement('div');
        commentDiv.className = 'comment-card fade-in';
        commentDiv.innerHTML = `
            <div class="d-flex justify-content-between align-items-start">
                <div>
                    <div class="comment-rating">
                        ${'★'.repeat(comment.rating)}${'☆'.repeat(5-comment.rating)}
                    </div>
                    <span class="badge bg-secondary">${comment.category}</span>
                </div>
                <small class="comment-meta">${comment.created_at}</small>
            </div>
            <div class="comment-content">${escapeHtml(comment.content)}</div>
        `;
        container.appendChild(commentDiv);
    });
}

// 加载统计数据
async function loadStats() {
    try {
        const response = await fetch('/api/stats');
        const stats = await response.json();
        
        // 更新基本信息
        document.getElementById('avgRating').textContent = stats.average_rating || '0';
        document.getElementById('totalComments').textContent = stats.total || '0';
        
        // 更新图表
        updateRatingChart(stats.rating_distribution);
        updateWordCloud(stats.keywords);
        updateCategoryStats(stats.category_stats);
        
    } catch (error) {
        console.error('加载统计数据失败:', error);
    }
}

// 更新评分分布图表
function updateRatingChart(distribution) {
    const ctx = document.getElementById('ratingChart').getContext('2d');
    
    if (ratingChart) {
        ratingChart.destroy();
    }
    
    const labels = [1, 2, 3, 4, 5];
    const data = labels.map(rating => distribution[rating] || 0);
    
    ratingChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: labels.map(r => r + '星'),
            datasets: [{
                label: '评论数量',
                data: data,
                backgroundColor: 'rgba(0, 123, 255, 0.7)',
                borderColor: 'rgba(0, 123, 255, 1)',
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        stepSize: 1
                    }
                }
            }
        }
    });
}

// 更新关键词云
function updateWordCloud(keywords) {
    const container = document.getElementById('wordCloud');
    container.innerHTML = '';
    
    if (!keywords || keywords.length === 0) {
        container.innerHTML = '<p class="text-muted">暂无关键词</p>';
        return;
    }
    
    keywords.forEach(keyword => {
        const tag = document.createElement('span');
        tag.className = 'keyword-tag';
        tag.textContent = keyword;
        tag.style.fontSize = (1 + Math.random() * 0.5) + 'rem';
        container.appendChild(tag);
    });
}

// 更新分类统计
function updateCategoryStats(stats) {
    const container = document.getElementById('categoryStats');
    container.innerHTML = '';
    
    if (!stats || Object.keys(stats).length === 0) {
        container.innerHTML = '<p class="text-muted text-center">暂无数据</p>';
        return;
    }
    
    Object.entries(stats).forEach(([category, data]) => {
        const col = document.createElement('div');
        col.className = 'col-md-4 col-sm-6 mb-3';
        col.innerHTML = `
            <div class="stat-card">
                <div class="stat-number">${data.count}</div>
                <div class="stat-label">${category}</div>
                <small class="text-muted">平均 ${data.avg_rating} 分</small>
            </div>
        `;
        container.appendChild(col);
    });
}

// 提交评论
async function submitComment() {
    const form = document.getElementById('commentForm');
    const formData = new FormData(form);
    
    const data = {
        rating: parseInt(document.getElementById('ratingInput').value),
        content: form.querySelector('textarea[name="content"]').value,
        category: form.querySelector('select[name="category"]').value
    };
    
    if (!data.rating || !data.content.trim()) {
        alert('请填写完整信息');
        return;
    }
    
    try {
        const response = await fetch('/api/comments', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data)
        });
        
        const result = await response.json();
        
        if (response.ok) {
            // 重置表单
            form.reset();
            setRating(0);
            
            // 关闭模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('commentModal'));
            modal.hide();
            
            // 重新加载数据
            loadComments();
            loadStats();
            
            alert('评论提交成功！');
        } else {
            alert(result.error || '提交失败');
        }
    } catch (error) {
        console.error('提交评论失败:', error);
        alert('提交失败，请重试');
    }
}

// 管理功能
function toggleAdmin() {
    if (isAdmin) {
        adminLogout();
    } else {
        const modal = new bootstrap.Modal(document.getElementById('adminModal'));
        modal.show();
    }
}

async function adminLogin() {
    const password = document.getElementById('adminPassword').value;
    
    try {
        const response = await fetch('/admin/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ password })
        });
        
        const result = await response.json();
        
        if (response.ok) {
            isAdmin = true;
            const modal = bootstrap.Modal.getInstance(document.getElementById('adminModal'));
            modal.hide();
            
            loadAdminComments();
            const adminPanel = new bootstrap.Modal(document.getElementById('adminPanel'));
            adminPanel.show();
        } else {
            alert(result.error || '登录失败');
        }
    } catch (error) {
        console.error('登录失败:', error);
        alert('登录失败，请重试');
    }
}

async function loadAdminComments() {
    try {
        const response = await fetch('/admin/comments');
        const comments = await response.json();
        
        const container = document.getElementById('adminCommentsList');
        container.innerHTML = '';
        
        comments.forEach(comment => {
            const item = document.createElement('div');
            item.className = 'admin-comment-item list-group-item';
            item.innerHTML = `
                <div class="d-flex justify-content-between align-items-start">
                    <div class="flex-grow-1">
                        <div class="d-flex align-items-center mb-2">
                            <span class="badge bg-primary me-2">${comment.category}</span>
                            <div class="text-warning">
                                ${'★'.repeat(comment.rating)}${'☆'.repeat(5-comment.rating)}
                            </div>
                        </div>
                        <p class="mb-1">${escapeHtml(comment.content)}</p>
                        <small class="text-muted">${comment.created_at}</small>
                    </div>
                    <div class="btn-group btn-group-sm ms-3">
                        <button class="btn btn-outline-danger btn-sm" onclick="deleteComment(${comment.id})">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </div>
            `;
            container.appendChild(item);
        });
    } catch (error) {
        console.error('加载管理评论失败:', error);
    }
}

async function deleteComment(id) {
    if (!confirm('确定要删除这条评论吗？')) return;
    
    try {
        const response = await fetch(`/admin/comments/${id}`, {
            method: 'DELETE'
        });
        
        if (response.ok) {
            loadAdminComments();
            loadComments();
            loadStats();
            alert('删除成功');
        } else {
            alert('删除失败');
        }
    } catch (error) {
        console.error('删除评论失败:', error);
        alert('删除失败，请重试');
    }
}

async function adminLogout() {
    try {
        await fetch('/admin/logout', { method: 'POST' });
    } catch (error) {
        console.error('退出失败:', error);
    }
    
    isAdmin = false;
    const adminPanel = bootstrap.Modal.getInstance(document.getElementById('adminPanel'));
    if (adminPanel) adminPanel.hide();
}

// 工具函数
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// 监听模态框关闭事件
document.getElementById('adminPanel').addEventListener('hidden.bs.modal', function () {
    if (isAdmin) {
        adminLogout();
    }
});
